package com.example.spring_mysql.redis


import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.dao.DataAccessException
import org.springframework.data.redis.connection.*
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
import org.springframework.data.redis.listener.PatternTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.stereotype.Component
import java.lang.RuntimeException
import java.util.concurrent.CompletableFuture

/**
 * 消息订阅配置
 *
 * @Author 程序员Mars
 * @date 2023/9/8 15:13
 */
@Configuration
@ConditionalOnProperty(name = ["redis.listener.enable"], havingValue = "true")
class RedisMessageConfiguration {

    @Autowired
    lateinit var serviceToWsListener: ServiceToWsListener


    companion object {
        const val WS_TO_SERVICE: String = "channel:ws_to_service"
    }

    @Bean
    fun redisConnectionFactory(): RedisConnectionFactory {
        return try {
            LettuceConnectionFactory("localhost", 6379).apply { afterPropertiesSet() }
        } catch (e: Exception) {
            println("Redis连接失败，将继续启动应用：${e.message}")
            // 返回一个 mock 的连接工厂，避免启动失败
            object : RedisConnectionFactory {
                override fun translateExceptionIfPossible(ex: RuntimeException): DataAccessException? {
                    throw IllegalStateException("Redis不可用")
                }

                override fun getConvertPipelineAndTxResults(): Boolean {
                    throw IllegalStateException("Redis不可用")
                }

                override fun getConnection(): RedisConnection {
                    throw IllegalStateException("Redis不可用")
                }

                override fun getClusterConnection(): RedisClusterConnection {
                    throw IllegalStateException("Redis不可用")
                }

                override fun getSentinelConnection(): RedisSentinelConnection {
                    throw IllegalStateException("Redis不可用")
                }
            }
        }
    }

    /**
     * 配置订阅关系
     */
//    @Bean
//    fun container(redisConnectionFactory: RedisConnectionFactory): RedisMessageListenerContainer {
//        val container: RedisMessageListenerContainer = RedisMessageListenerContainer()
//        container.setConnectionFactory(redisConnectionFactory)
//        // 订阅的channel
//        val patternTopic2: PatternTopic = PatternTopic(WS_TO_SERVICE)
//        container.addMessageListener(serviceToWsListener, patternTopic2)
//        return container
//    }


}
